import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  TouchableOpacity,
  Button,
  Alert,
  AlertIOS,
  FlatList,
  ListView,
  ScrollView,
} from 'react-native';

import { Icon } from 'react-native-elements';
import { List, ListItem, } from 'react-native-elements';
import { globalStyles }  from './StyleSheet';
import { dataManager } from './dataManager';
import MiniAudioPlayer from './MiniAudioPlayer';




type Props = {};
export default class LibraryView extends Component<Props> {

  state = {
    playlists: [],
    inEditMode: false,
    
  };


  static navigationOptions = ({ navigation }) => {

    const params = navigation.state.params || {};

    if (params.screenStateParams == false) {
      return {
        title: 'Library',
        headerStyle: {
          backgroundColor: '#3C3C3C', 

        } ,
        headerTintColor: '#DDDDDD',
        headerRight: (
          <View style={{flex: 1, flexDirection: 'row'}}>

            <Icon
              name="center-focus-weak"
              color="#DDDDDD"
              onPress={() => params.navigateToScanParams()}
              />

            <Button
              onPress={() => params.editModeParams()}
              title='Edit'
              color="#DDDDDD"

            />

          </View>
        ), 
        headerLeft: (
          <View style={{marginLeft: 10}}>

            <Icon
              onPress={params.navigateToProfileParams}
              name="account-circle"
              color="#DDDDDD"
            />
          </View>
    ),
      };
    } 
    else {
      return {
        title: 'Library',
        headerStyle: {
          backgroundColor: '#3C3C3C' 
        } ,
        headerTintColor: '#DDDDDD',
        headerRight: (
          <View style={{flexDirection: 'row'}}>
            <Button
              onPress={() => params.returnToLibraryViewParams() }
              title='Done'
              color="#74F8F7"
            />

          </View>
        ), 
      };
    };      
  };



  componentWillMount() {
    this.props.navigation.setParams({screenStateParams: this.state.inEditMode})
    this.props.navigation.setParams({editModeParams: this.editModeView})    
    this.props.navigation.setParams({navigateToScanParams: this.navigateToScan})
    this.props.navigation.setParams({navigateToProfileParams: this.navigateToProfile})
    this.props.navigation.setParams({returnToLibraryViewParams: this.returnToLibraryView})
  
    this.loadPlaylistData();

  };

  loadPlaylistData = () => {
    global.dataManager.getAllPlaylists()
    .then((playlists) => {
      console.log("LibraryView: Playlists have been obtained.", playlists);
      this.setState({"playlists": playlists});
    });
  }

  editModeView = () => {this.setState({inEditMode: true})
    this.componentWillMount()
  };

  returnToLibraryView = () => {this.setState({inEditMode: false})
    this.componentWillMount()
  };

  navigateToScan = () => {this.props.navigation.navigate("QrCodeScanner")};


  navigateToProfile = () => {this.props.navigation.navigate("profileView")};

  promptNewPlaylist = () => {
    AlertIOS.prompt(
      'Playlist Name',
      null,
      text => {
        // obtained the text!
        dataManager.createPlaylistWithTitle(text)
        .then((playlistInfo) => {
          this.props.navigation.navigate("PlaylistContent", {playlistId: playlistInfo.uid});
        });
      }
    );
  };

  renamePlaylist = (text) => { return (
    <TextInput
      style={globalStyles.appMainText}
      //onChangeText={(text) => //change playlist.title}
      //onSubmitEditing= //use this istead to change on submit button press
      value={(text)}
    />
    )
  };

  parseTime(timestamp) {
    
    var date = new Date(timestamp);
    var day = date.getDay(timestamp);
    var month = date.getMonth(timestamp)
    var dayOfMonth = date.getDate(timestamp)
    var year = date.getFullYear(timestamp)

    var displayedDate = (month)+ "/" + (dayOfMonth) + "/" + (year)

    return displayedDate.toString();
  };

  render() {

    return (
      <View style={styles.container}>


        <View style={styles.playlistContainer}>
          <ScrollView contentContainerStyle={{paddingTop: 0}}>
            <List containerStyle={styles.playlistButton}>
              {
                this.state.playlists.map((playlistInfo) => {
                  if(this.state.inEditMode == true) {
                    return (
                       <ListItem 
                        roundAvatar
                        key={playlistInfo.uid}
                        title={this.renamePlaylist(playlistInfo.title)}
                        titleStyle={globalStyles.appMainText}
                        //avatar={{uri:rowData.avatar_url}} 
                        hideChevron
                        //rightTitle={this.parseTime(playlistInfo.creationTime)}
                        underlayColor={"#474646"}
                        leftIcon={{name: 'delete-forever', color: 'red'}}
                        leftIconOnPress={() => {
                            AlertIOS.alert(
                              'Alert',
                              'Are you sure you wish to permanently delete this playlist?',
                              [
                                {
                                  text: 'Cancel',
                                  onPress: () => console.log('Cancel Delete'),          
                                  style: 'cancel',
                                },
                                {
                                  text: 'Delete',
                                  style: 'destructive',

                                  onPress: () => {dataManager.deletePlaylistById(playlistInfo.uid)
                                    this.componentWillMount()
                                  }

                                },
                              ]
                            ); 
                          }
                        }

                    />);

                  }
                  else {
                    return (
                      <ListItem 
                        roundAvatar
                        key={playlistInfo.uid}
                        title={playlistInfo.title}
                        titleStyle={globalStyles.appMainText}
                        subtitle={(playlistInfo.notes ? playlistInfo.notes + "," : "") + " " + playlistInfo.items.length + " items"}
                        //avatar={{uri:rowData.avatar_url}} 
                        onPress={() => this.props.navigation.navigate("PlaylistContent", 
                            {
                              "playlistId": playlistInfo.uid,
                              "onReturn": this.loadPlaylistData
                            }
                        )}
                        hideChevron
                        rightTitle={this.parseTime(playlistInfo.creationTime)}
                        underlayColor={"#474646"}
                        //rightIcon={{name: 'file-download'}}
                        onPressRightIcon={() => alert("download")}
                       

                    />);
                  }
                  
                })
              }
            </List>
          </ScrollView>
          <TouchableOpacity
            style={styles.playlistContainerBottom}
            onPress={() => this.promptNewPlaylist()}
          >
             <Icon
                color= '#74F8F7'
                size={50}
                name="add-circle"
              />
              <Text style={globalStyles.appMainText}>New Playlist</Text>
          </TouchableOpacity>
             
        </View>


          <MiniAudioPlayer onPress={() => {this.props.navigation.navigate("FullscreenAudioPlayer")}}/>


      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#ffffff',
  },
/*  headerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ADADAD',
  },*/
  playlistContainer: {
    flex: 7,
    flexDirection: 'column',
    backgroundColor: '#3C3C3C',
    justifyContent: 'flex-start',
  },
  playlistContainerBottom: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#3C3C3C',
    alignItems: 'center',
    marginBottom: 10
  },

  playlistButton: {
    flexDirection: 'column',
    justifyContent: 'flex-start',
    backgroundColor: '#333',
    marginTop: 0
  },
  playerContainer: {
    height:300,
    backgroundColor: "#333",
    flex:1,
  },
  red: {
    color: 'red'
  },

});
